package com.bidevalution.business.function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.support.util.StringUtil;
import com.qtp.core.util.OConvertUtils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;
import com.qtp.core.redis.RedisUtil;
import com.qtp.core.util.GsonUtil;

/**
 * 执行sql语句
 * 
 * @author daizhifeng
 * @date 2019-08-06
 */
public class SqlExecutorFunction extends AbstractFunction {
	private FunctionInitializer functionInitializer;
	private Logger logger = LogManager.getLogger(getClass());
	public SqlExecutorFunction(FunctionInitializer functionInitializer) {
		super();
		this.functionInitializer = functionInitializer;
	}

	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1,AviatorObject arg2){
		String sqlKey = arg1.getValue(env).toString();
		String queryType = arg2.getValue(env).toString();
		String sql = RedisUtil.get(sqlKey);
		logger.info(env+",sql:"+sql);
		// 获取ql语句的参数值
		if(!StringUtils.isEmpty(sql)) {
			Map<String,Object> paramMap = new HashMap<String, Object>();
			for(String paramName:StringUtil.getParamNameList(sql)) {
				if(env.containsKey("$"+paramName)) {

					paramMap.put(paramName.trim(), env.get("$"+paramName));
				}else if(env.containsKey(paramName)){

					paramMap.put(paramName.trim(), env.get(paramName));
				}
			}

			if("COUNT".equals(queryType)) {

				Integer cntInteger = functionInitializer.getJdbcTemplateService().selectForObject(sql, paramMap, Integer.class);
				if(cntInteger == null) {
					return new AviatorDouble(0);
				}
				return new AviatorDouble(cntInteger);
			}else if("LIST".equals(queryType)) {
				return new AviatorString(GsonUtil.toJson(functionInitializer.getJdbcTemplateService().selectForList(sql, paramMap)));
			}else if("MAP".equals(queryType)) {
				return new AviatorString(GsonUtil.toJson(functionInitializer.getJdbcTemplateService().selectForMap(sql, paramMap)));
			}else if("ARRAY".equals(queryType)) {
				return new AviatorString(StringUtils.arrayToDelimitedString(functionInitializer.getJdbcTemplateService().selectForList(sql, paramMap, String.class).toArray(), ","));
			}
			return new AviatorString("");
		}else {
			return new AviatorString("");
		}
	}

	@Override
	public String getName() {
		return "sqlExecutor";
	}
	

}
